package com.mxx.common.netty.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mxx.common.conv.CustomObjectMapper;
import com.mxx.common.conv.JacksonConverter;
import com.mxx.common.netty.NettyHttpOperator;
import com.mxx.common.netty.exception.ExceptionCatcherByHttp;
import com.mxx.common.netty.exception.ExceptionCatcherByHttpImpl;
import com.mxx.common.netty.http.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/7/17 18:10
 * @Description: 加载Http 基本类
 */
@Configuration
@ComponentScans({
        @ComponentScan("com.mxx.common.netty.http.resolvers"),
})
public class LoadNettyHttpComponent {
    @Value("${server.servlet.context-path:/}")
    private String contextPath;


    /**
     * http 异常处理注入
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new CustomObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper;
    }

    @Bean
    @ConditionalOnMissingBean(ExceptionCatcherByHttp.class)
    public ExceptionCatcherByHttp exceptionCatcherByHttpImpl() {
        return new ExceptionCatcherByHttpImpl();
    }

    @Bean
    @ConditionalOnMissingBean(JacksonConverter.class)
    public JacksonConverter jacksonConverter(ObjectMapper objectMapper) {
        return JacksonConverter.getInstance(objectMapper);
    }

    @Bean
    @ConditionalOnMissingBean(NettyHttpResponseTemplate.class)
    public NettyHttpResponseTemplate nettyHttpResponseTemplate() {
        return new DefaultNettyHttpResponseTemplate();
    }

    @Bean
    @ConditionalOnMissingBean(NettyHttpResponseFactory.class)
    public NettyHttpResponseFactory nettyHttpResponseFactory(JacksonConverter jacksonConverter, NettyHttpResponseTemplate nettyHttpResponseTemplate) {
        return new DefaultNettyHttpResponseFactory(jacksonConverter, nettyHttpResponseTemplate);
    }


    /**
     * http 处理器操作类注入
     *
     * @return
     */

    @Bean
    @ConditionalOnMissingBean(NettyHttpOperator.class)
    public NettyHttpOperator defaultNettyHttpOperator() {
        return new DefaultNettyHttpOperator(contextPath);
    }


    /**
     * http 操作类注入
     *
     * @param httpOperator
     * @return
     */
    @Bean
    public NettyHttpHandler nettyHttpHandler(NettyHttpOperator httpOperator) {
        return new NettyHttpHandler(httpOperator);
    }


}
